package convert.converter;


import com.opencsv.CSVWriter;
import org.yaml.snakeyaml.Yaml;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class yaml_to_csv {

    public static void main(String[] args) {
        String yamlFilePath = "src/resource/yaml/output.yaml";
        String csvFilePath = "src/resource/csv/yaml_output.csv";

        convertYAMLToCSV(yamlFilePath, csvFilePath);
    }

    public static void convertYAMLToCSV(String yamlFilePath, String csvFilePath) {
        try {
            Yaml yaml = new Yaml();
            FileReader reader = new FileReader(yamlFilePath);

            // Load YAML data into a List of Maps
            List<Map<String, String>> dataList = yaml.load(reader);

            reader.close();

            // Extract headers from the first row
            String[] headers = dataList.get(0).keySet().toArray(new String[0]);

            FileWriter writer = new FileWriter(csvFilePath);
            CSVWriter csvWriter = new CSVWriter(writer);

            // Write headers to CSV file
            csvWriter.writeNext(headers);

            // Write data rows to CSV file
            for (Map<String, String> row : dataList) {
                String[] rowData = new String[headers.length];
                for (int i = 0; i < headers.length; i++) {
                    String header = headers[i];
                    String value = row.get(header);
                    rowData[i] = value != null ? value : "";
                }
                csvWriter.writeNext(rowData);
            }

            csvWriter.close();

            System.out.println("YAML to CSV conversion completed successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
